using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataFactoryEventManager : MonoBehaviour
{
    public static DataFactoryEventManager Instance;
    Dictionary<int, IDataFactory> ctrlEventHandlers;
    private void Awake()
    {
        Instance = this;
        ctrlEventHandlers = new Dictionary<int, IDataFactory>(32);
    }

    private void OnEnable()
    {
        EventDispatchManager.Instance.AddEvent(CtrlEventID.EVENT_CONNECT_CTRL, HandleCtrlConnect);
        EventDispatchManager.Instance.AddEvent(CtrlEventID.EVENT_CONNECT_DATA_CENTER, OnEventFactoryConnect);
        EventDispatchManager.Instance.AddEvent(CtrlEventID.EVENT_QUERY_DATA_FACTORY_DATA, OnEventQueryFactory);
    }

    private void OnDisable()
    {
        EventDispatchManager.Instance.RemoveEvent(CtrlEventID.EVENT_QUERY_DATA_FACTORY_DATA, OnEventQueryFactory);
        EventDispatchManager.Instance.RemoveEvent(CtrlEventID.EVENT_CONNECT_DATA_CENTER, OnEventFactoryConnect);
        EventDispatchManager.Instance.RemoveEvent(CtrlEventID.EVENT_CONNECT_CTRL, HandleCtrlConnect);
    }

    void OnEventFactoryConnect(IEventArgv eventArgv)
    {
        if(eventArgv is EventArgv<IDataFactory> argv)
        {
            ctrlEventHandlers[argv.a.ID] = argv.a;
        }
    }

    void OnEventQueryFactory(IEventArgv eventArgv)
    {
        if (eventArgv is EventArgv<int> argv)
        {
            if (ctrlEventHandlers.TryGetValue(argv.a, out var dataFactory))
            {
                dataFactory.QueryData();
            }
        }
    }

    void HandleCtrlConnect(IEventArgv eventArgv)
    {
        if(eventArgv is EventArgv<CtrlEventHandler,int> argvs)
        {
            if (ctrlEventHandlers.TryGetValue(argvs.a.DataFactoryId,out var dataFactory))
            {
                var param = dataFactory.Get(argvs.b);
                if(null != param)
                {
                    argvs.a.Bind(param);
                }
            }
        }
    }

    private void OnDestroy()
    {
        ctrlEventHandlers.Clear();
        Instance = null;
    }
}
